package lk.icta.common.dao.impl;

import lk.icta.common.dao.DocumentManagementDao;
import lk.icta.common.entity.Document;
import lk.icta.common.entity.DocumentCategory;
import lk.icta.core.entity.Land;
import lk.icta.core.entity.ModuleType;
import lk.icta.user.entity.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.List;

/**
 * @author Mahesha Kalpanie
 */
public class DocumentManagementDaoImpl extends BaseDAO implements DocumentManagementDao {

    @Transactional(propagation = Propagation.MANDATORY)
    public void addDocument(User user, Document document) {
        logger.debug("Adding a Document : {}", user.getUsername());
        em.persist(document);
    }

    @Transactional(propagation = Propagation.MANDATORY)
    public void updateDocument(User user, Document document) {
        logger.debug("Updating the document : {}", user.getUsername());
        em.merge(document);
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public List<Document> getDocumentsByModuleAndModuleId(User user, ModuleType module, long moduleId) {
        logger.debug("Find Document by module and module Id : {}", user.getUsername());
        Query q = em.createNamedQuery("getDocumentsByModuleAndModuleId");
        q.setParameter("moduleType", module);
        q.setParameter("moduleId", moduleId);
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public Document getDocumentById(User user, long id) {
        logger.debug("Find Document by Id : {}", user.getUsername());
        return em.find(Document.class, id);
    }

    @Transactional(propagation = Propagation.MANDATORY)
    public void deleteDocumentById(User user, long id) {
        logger.debug("delete Document by Id : {}", user.getUsername());
        Document doc = em.find(Document.class, id);
        if (doc != null) {
            em.remove(doc);
            em.flush();
        }
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<DocumentCategory> getDocumentCategoryList(User user) {
        logger.debug("get Document Category List {} ", user.getUsername());
        Query q = em.createNamedQuery("getDocumentCategoryList");
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<DocumentCategory> getDocumentCategoryListByModuleId(User user, ModuleType moduleType) {
        logger.debug("get Document Category List {} ", user.getUsername());
        Query q = em.createNamedQuery("getDocumentCategoryListByModuleId");
        q.setParameter("moduleId", moduleType.getId());
        return q.getResultList();
    }
}
